package com.zhang.es;

import com.google.gson.Gson;
import com.zhang.model.User;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Before;
import org.junit.Test;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

/**
 * @program: elasitcsearch
 * @description:
 * @author: Dawson.Zhang
 * @create: 2020-03-14
 **/
public class fuxiday3 {
    private TransportClient client;
    @Before
    public void createClient() throws Exception {
        Settings settings = Settings.builder().put("cluster.name","my-elasticsearch").build();
        client = new PreBuiltTransportClient(settings)
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.117.131"),9301))
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.117.130"),9302));
    }

    @Test
    public void addIndex(){
        client.admin().indices().prepareCreate("java2").get();
        client.close();
    }
    @Test
    public void addMappings()throws Exception{
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject()
                    .startObject("user")
                        .startObject("properties")
                            .startObject("id")
                                .field("type","long")
                                .field("index",true)
                                .field("store",true)
                            .endObject()
                            .startObject("userName")
                                .field("type","text")
                                .field("index",true)
                                .field("store",true)
                                .field("analyzer","ik_smart")
                            .endObject()
                        .endObject()
                    .endObject()
                .endObject();
        client.admin().indices().preparePutMapping("java2").setType("user").setSource(builder).get();
        client.close();
    }

    @Test
    public void addDoc(){
        for (int i = 0; i < 20; i++) {
            User user = new User(i, "性情的修养，不是为了别人，而是为自己增强生活能力。修养的基础是内心对话，人在这种对话中既是自己的原告，又是自己的辩护士和法官。修养之于心地，其重要犹如食物之于身体。以一般人而言，最简便的修养方法是读书。有教养的人或受过理想教育的人，不一定是个博学的人，而是个知道何所爱何所恶的人。" + i + "");
            Gson gson = new Gson();
            String s = gson.toJson(user);
            client.prepareIndex()
                  .setIndex("java2")
                  .setType("user")
                  .setSource(s)
                  .setId("编号"+i+"")
                  .get();
        }
        client.close();
    }
    @Test
    public void searCh(){
        QueryBuilder builder = QueryBuilders.boolQuery().must(QueryBuilders.queryStringQuery("4"));

        SearchResponse searchResponse = client.prepareSearch()
            .setIndices("java2")
            .setTypes("user")
            .setQuery(builder)
            .get();

        SearchHits hits = searchResponse.getHits();
        System.out.println(hits.getTotalHits()+"总条数");
        SearchHit[] hits1 = hits.getHits();
        for (SearchHit searchHitFields : hits1) {
            System.out.println(searchHitFields.getSourceAsString());
            Map<String, Object> source = searchHitFields.getSource();
            System.out.println(source.get("id"));
            System.out.println(source.get("userName"));
        }
        client.close();
    }
    @Test
    public void getHigh(){
        HighlightBuilder builder = new HighlightBuilder().field("userName").preTags("<span style='red'>")
            .postTags("<span>");

        QueryBuilder queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.queryStringQuery("人生").defaultField("userName"));

        SearchResponse searchResponse = client.prepareSearch()
            .setIndices("java2")
            .setTypes("user")
            .setFrom(0)
            .setSize(4)
            .setQuery(queryBuilder)
            .highlighter(builder)
            .get();

        SearchHits searchHits = searchResponse.getHits();

        System.out.println(searchHits.getTotalHits()+"总条数");

        SearchHit[] hitsHits = searchHits.getHits();
        for (SearchHit hitsHit : hitsHits) {

            Map<String, Object> source = hitsHit.getSource();
            System.out.println(source.get("id"));
            System.out.println(source.get("userName"));

            Map<String, HighlightField> highlightFields = hitsHit.getHighlightFields();
            HighlightField userName1 = highlightFields.get("userName");
            Text[] fragments = userName1.fragments();
            for (Text fragment : fragments) {
                System.out.println(fragment);
            }

            client.prepareDelete().setIndex("java2").setType("user").setId(String.valueOf(hitsHit.getId())).get();
        }
    }
    @Test
    public void delDoc(){

    }
}
